package com.course.cdspringboot.security;

import com.course.cdspringboot.mapper.UserMapper;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.server.ResponseStatusException;

import java.util.HashMap;
import java.util.Map;

@Component
public class RoleAccessControl {

    @Autowired
    private UserMapper userMapper;



    public Long checkAccess(String... allowedRoles) {
        ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = null;
        if (attributes != null) {
            request = attributes.getRequest();
        }

        String username = null;
        if (request != null) {
            username = (String) request.getAttribute("username");
        }

        Map<String, Object> user = userMapper.findByUsername(username);

        if (user == null) {
            throw new ResponseStatusException(HttpStatus.FORBIDDEN, "User not found");
        }
        Long userId = (Long) user.get("uid");
        String userName = (String) user.get("username");

        Map<String, Object> userRole = userMapper.findRoleByUserId(userId);
        String roleName = "";

        if (userRole != null) {
            roleName = userRole.get("name").toString();
        }

//        System.out.println("RAC:userRole:"+userRole.getName());


        boolean hasAllowedRole = false;
        for (String allowedRole : allowedRoles) {
            if (roleName.equals(allowedRole)) {
                hasAllowedRole = true;
                break;
            }
        }

        if (!hasAllowedRole) {
            throw new ResponseStatusException(HttpStatus.FORBIDDEN, "Access denied");
        }

//        Map<String, Object> result = new HashMap<>();
//        result.put("uid", user.get("uid"));
//        result.put("roleName", roleName);

        return (Long) user.get("uid");
    }
}